﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.Text;
public class MessageHandler : MonoBehaviour
{
    public static MessageHandler get = null;
    private void Awake()
    {
        get = this;
    }
    //根据发送数据得到byte数组
    public byte[] GetMessage(int type, string obj)
    {
        Message message = new Message(type, obj);
        string msg= JsonMapper.ToJson(message);
        return Encoding.UTF8.GetBytes(msg);
    }
    //接受到数据转换为消息类，方便广播
    public void Recive(int count, byte[] data)
    {
        string msg = Encoding.UTF8.GetString(data, 0, count);
        JsonData jsonData= JsonMapper.ToObject(msg);
        int jsonType = (int)jsonData[0];
        string jsonMsg = (string)jsonData[1];
        Message message = new Message(jsonType,jsonMsg);
        allMessage.Add(message);
    }
    private List<Message> allMessage = new List<Message>();
    private void Update()
    {
        if (allMessage.Count != 0)
        {
            for (int i = 0; i < allMessage.Count; i++)
            {
                if (SocketManager.reciveDelegate != null)
                {
                    SocketManager.reciveDelegate.Invoke(allMessage[i].type, allMessage[i].msg);
                }
            }
            allMessage.Clear();
        }
    }
    //消息类
    class Message
    {
        public int type;
        public string msg;
        public Message(int type, string msg)
        {
            this.type = type;
            this.msg = msg;
        }
    }
}
